<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理员登录 - 权益明账通</title>
    <style>
        /* 全局样式 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Helvetica Neue', Arial, sans-serif;
            background: linear-gradient(135deg, #1976d2, #2196f3);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }

        /* 登录卡片 */
        .login-container {
            background: white;
            border-radius: 12px;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
            padding: 40px;
            width: 100%;
            max-width: 400px;
            position: relative;
        }

        .login-header {
            text-align: center;
            margin-bottom: 30px;
        }

        .login-header h1 {
            color: #1976d2;
            font-size: 24px;
            margin-bottom: 10px;
            font-weight: 600;
        }

        .login-header p {
            color: #666;
            font-size: 14px;
        }

        .admin-badge {
            background: #ff9800;
            color: white;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            display: inline-block;
            margin-top: 5px;
        }

        /* 表单样式 */
        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #555;
            font-weight: 500;
            font-size: 14px;
        }

        .form-control {
            width: 100%;
            padding: 12px 15px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
            transition: all 0.3s;
        }

        .form-control:focus {
            outline: none;
            border-color: #1976d2;
            box-shadow: 0 0 0 3px rgba(25, 118, 210, 0.1);
        }

        .btn-login {
            width: 100%;
            background: #1976d2;
            color: white;
            border: none;
            padding: 12px;
            border-radius: 6px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: background 0.3s;
            margin-top: 10px;
        }

        .btn-login:hover {
            background: #1565c0;
        }

        .btn-login:disabled {
            background: #90caf9;
            cursor: not-allowed;
        }

        /* 消息提示 */
        .message {
            padding: 10px;
            border-radius: 4px;
            margin-top: 15px;
            font-size: 14px;
            display: none;
        }

        .message.error {
            background: #ffebee;
            color: #f44336;
            border: 1px solid #ffcdd2;
        }

        .message.success {
            background: #e8f5e9;
            color: #4caf50;
            border: 1px solid #c8e6c9;
        }

        /* 页脚 */
        .login-footer {
            text-align: center;
            margin-top: 20px;
            padding-top: 20px;
            border-top: 1px solid #eee;
            font-size: 12px;
            color: #999;
        }

        .back-link {
            color: #1976d2;
            text-decoration: none;
            font-size: 14px;
            display: inline-block;
            margin-top: 15px;
        }

        .back-link:hover {
            text-decoration: underline;
        }

        /* 加载动画 */
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 2px solid #ffffff;
            border-radius: 50%;
            border-top-color: transparent;
            animation: spin 1s ease-in-out infinite;
            margin-right: 10px;
            vertical-align: middle;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        /* 移动端适配 */
        @media (max-width: 480px) {
            .login-container {
                padding: 30px 20px;
            }

            body {
                padding: 10px;
            }
        }
    </style>
</head>
<body>
<div class="login-container">
    <div class="login-header">
        <h1>权益明账通</h1>
        <p>管理员后台系统</p>
        <div class="admin-badge">管理员登录</div>
    </div>

    <form id="loginForm">
        <div class="form-group">
            <label for="username">管理员账号</label>
            <input type="text" id="username" name="username" class="form-control" placeholder="请输入管理员账号" required>
        </div>

        <div class="form-group">
            <label for="password">密码</label>
            <input type="password" id="password" name="password" class="form-control" placeholder="请输入密码" required>
        </div>

        <button type="submit" class="btn-login" id="loginBtn">
            <span id="loginText">登录</span>
        </button>

        <div id="message" class="message"></div>
    </form>

    <div class="login-footer">
        <p>© 2025 权益明账通 - 管理员系统</p>
        <a href="./index.html" class="back-link">← 返回前台首页</a>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const loginForm = document.getElementById('loginForm');
        const usernameInput = document.getElementById('username');
        const passwordInput = document.getElementById('password');
        const loginBtn = document.getElementById('loginBtn');
        const loginText = document.getElementById('loginText');
        const message = document.getElementById('message');

        // Cookie操作函数
        function getCookie(name) {
            const cookies = document.cookie.split(';');
            for (let cookie of cookies) {
                const [cookieName, cookieValue] = cookie.trim().split('=');
                if (cookieName === name) {
                    return decodeURIComponent(cookieValue);
                }
            }
            return '0'; // 如果没有找到，返回'0'
        }

        function setCookie(name, value, days = 7) {
            const date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            const expires = "expires=" + date.toUTCString();
            document.cookie = name + "=" + encodeURIComponent(value) + ";" + expires + ";path=/";
        }

        // 页面加载时尝试从cookie填充用户名
        const savedUsername = getCookie('username');
        if (savedUsername && savedUsername !== '0') {
            usernameInput.value = savedUsername;
        }

        // 表单提交
        loginForm.addEventListener('submit', async function(e) {
            e.preventDefault();

            // 基础验证
            const username = usernameInput.value.trim();
            const password = passwordInput.value.trim();

            if (!username || !password) {
                showMessage('请输入完整的登录信息', 'error');
                return;
            }

            // 禁用按钮并显示加载状态
            loginBtn.disabled = true;
            loginText.innerHTML = '<span class="loading"></span>登录中...';
            hideMessage();

            try {
                // 从cookie获取authid和authtoken
                const authid = getCookie('authid');
                const authtoken = getCookie('authtoken');

                // 调用登录API
                const result = await adminLogin(username, password, authid, authtoken);

                if (result.code === 200) {
                    showMessage('登录成功，正在跳转...', 'success');

                    // 保存用户信息到cookie
                    setCookie('username', result.data.username);
                    setCookie('password', result.data.password);
                    setCookie('authid', result.data.authid);
                    setCookie('authtoken', result.data.authtoken);

                    // 登录成功，在当前标签页跳转到ManageSystem.html
                    setTimeout(() => {
                        window.location.href = './ManageSystem.html';
                    }, 1000);
                } else {
                    // 登录失败，不跳转，显示错误信息
                    showMessage(result.msg || '登录失败', 'error');
                }
            } catch (error) {
                console.error('登录错误:', error);
                showMessage('网络错误，请检查连接后重试', 'error');
            } finally {
                // 恢复按钮状态
                loginBtn.disabled = false;
                loginText.textContent = '登录';
            }
        });

        // 显示消息
        function showMessage(text, type) {
            message.textContent = text;
            message.className = 'message ' + type;
            message.style.display = 'block';
        }

        // 隐藏消息
        function hideMessage() {
            message.style.display = 'none';
        }

        // 真实的API调用函数
        async function adminLogin(username, password, authid, authtoken) {
            try {
                const response = await fetch('/api/admin/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        username: username,
                        password: password,
                        authid: authid,
                        authtoken: authtoken
                    })
                });

                if (!response.ok) {
                    // 处理HTTP错误
                    const errorText = await response.text();
                    throw new Error(`HTTP ${response.status}: ${errorText}`);
                }

                const result = await response.json();

                // 返回原始响应数据
                return result;

            } catch (error) {
                console.error('API调用失败:', error);

                // 根据错误类型返回相应的错误信息
                if (error.name === 'TypeError' && error.message.includes('fetch')) {
                    throw new Error('网络连接失败，请检查网络设置');
                } else if (error.message.includes('HTTP 4')) {
                    return {
                        code: 0,
                        msg: '未登录',
                        data: null
                    };
                } else if (error.message.includes('HTTP 5')) {
                    return {
                        code: 0,
                        msg: '服务器内部错误，请稍后重试',
                        data: null
                    };
                } else {
                    return {
                        code: 0,
                        msg: '登录请求失败',
                        data: null
                    };
                }
            }
        }

        // 示例：测试用的模拟登录（仅用于开发测试）
        async function mockAdminLogin(username, password, authid, authtoken) {
            // 模拟网络延迟
            await new Promise(resolve => setTimeout(resolve, 1000));

            // 模拟验证逻辑
            if (username === 'admin' && password === 'admin123') {
                return {
                    code: 200,
                    msg: '登录成功',
                    data: {
                        username: 'admin',
                        password: 'admin123',
                        authid: authid !== '0' ? authid : '123',
                        authtoken: authtoken !== '0' ? authtoken : '456'
                    }
                };
            } else {
                return {
                    code: 0,
                    msg: '未登录',
                    data: null
                };
            }
        }
    });
</script>
</body>
</html>